
var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate, colorpicker = layui.colorpicker,isFinance,paymentPurchaseNo=getQueryVariable("purchaseNo");

//是否有 工厂统计及费用方式 权限，如果有标签赋值true 并设置不显示
let factoryStatisticsCost=false;
factory_statistics_cost();
if (factoryStatisticsCost){
    document.getElementById("statisticsDiv").style.display = "none";
}

//工厂财务标签 有该标签:false 无该标签:true
let isFactoryFinance = true;
isFactoryFinance = getAllRolesByCurr("GCCWYF001");

function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(item["users"]){
            for(let it of item["users"]){
                item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJson(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}

function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,

        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            return this
        }
    })
}


let operationList=[];
let deptOperationList=[];
(function () {
    //获取当前用户的部门及人员结构树
    let treeList = getCurrentDepartmentUser();

    if(treeList && treeList.list){
        let userTree = getAllJson(treeList.list);
        operationList= getxmselect("#operationCode","operationCode", userTree)
    }else {
        operationList=getxmselect("#operationCode","operationCode", [{name: user.name, value: user.code}])
    }

    //获取当前用户所属部门树()
    let currentDeptTreeList = getAllUserDepartmentTree();
    if (currentDeptTreeList && currentDeptTreeList.list) {
        let deptTree = getAllJson(currentDeptTreeList.list);
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", deptTree);
    } else {
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", [{name: user.name, value: user.code}]);
    }

})()

lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});
layui.use(['dropdown'], function () {
    let dropdown = layui.dropdown;
    dropdown.onFilter("paymentStatistics", function (event) {
        switch (event) {
            case "s1":
                parent.intab("views/jsp/Money/tpl/paymentStatistics1.jsp","付款情况统计")
                break
            case "s2":
                parent.intab("views/jsp/ExportBusiness/tpl/carryDetailStatistics1.jsp", "按出运明细统计采购应付款")
                break
            case "s3":
                parent.intab("views/jsp/Money/tpl/paymentStatistics2.jsp","采购预付款统计")
                break
            case "s4":
                parent.intab("views/jsp/Money/tpl/paymentShipmentAmountStatistics.jsp","出货金额统计")
                break
            case "s5":
                parent.intab("views/jsp/Money/tpl/purchasePaymentStatistics.jsp","采购付款统计")
                break
        }
    });
})



layer.ready(function () {
    $.ajax({
        url: 'cost/isFinance',
        type: 'GET',
        async: false, // 同步
        success: function (date) {
            isFinance=date.data
        }
    })
    //获取所有公司信息
    $.ajax({
        url:"receivePayment/getCompanyInfo",
        success:function(data){
            if(data.status == 200){
                for(let i in data.data){
                    //公司名称
                    $('#companyCode').append(new Option(data.data[i].name, data.data[i].code));
                }
                form.render('select');
            }
        }
    });
});


form.render();
document.getElementById('clear').onclick = function(){
    operationList.setValue([ ]);
    deptOperationList.setValue([ ]);
};


table.render({
    elem: '#maininformation'
    ,where:{operationCode : user.code}
    ,url:'payment/getListByPage'
    ,toolbar: '#maininformationtoolbar'
    ,totalRow: true
    ,cols: [[
        {checkbox: true, fixed: true}
        ,{field:'numbers',width: 50,type:'numbers',title:'序号', totalRowText: '合计'}
        ,{field:'billNo', title:'付款单号',sort:true,width: 120,event: "paymentorderno"}
        ,{field:'time', title:'应付日期',sort:true,width: 120}
        ,{field:'createDate', title:'创建日期',sort:true,width: 120}
        ,{field:'typeStr', title:'付款类型',sort:true,width: 120}
        ,{field:'supplierName', title:'收款单位',sort:true,width: 120}
        ,{field:'bankName', title:'收款银行',sort:true,width: 120}
        ,{field:'bankAccount', title:'收款账号',sort:true,width: 120}
        ,{field:'actualPaymentDate', title:'实付日期',sort:true,width: 120}
        ,{field:'actualPaymentAmount', title:'实付金额',sort:true,width: 120, align: 'right', totalRow: true}
        ,{field:'currency', title:'币种',sort:true,width: 120}
        ,{field:'rmbRate', title:'人民币汇率',sort:true,width: 120, align: 'right'}
        ,{field:'usdRate', title:'美金汇率',sort:true,width: 120, align: 'right'}
        ,{field:'amount', title:'付款金额',sort:true,width: 120, align: 'right'}
        ,{field:'lastAmount', title:'剩余付款金额',sort:true,width: 120, align: 'right'}
        ,{field:'companyName', title:'制单公司',sort:true,width: 120}
        ,{field:'operation', title:'操作员',sort:true,width: 120}
        ,{field:'memo', title:'备注',sort:true,width: 120}
        ,{fixed: 'right', width:365, toolbar: '#maininformationeditor', title:'操作'}
    ]]
    ,id: 'maininformationtableid'
    ,height: $(document).height() - $('#maininformation').offset().top - 75
    ,page: true
    ,limit: 50
    ,limits: [50, 100, 200, 300, 500]
    , done(res, curr, count) {
        lay('.colorvalue').each(function () {
            let xb = $(this).attr("data-id");
            let colors = "";
            for (var i = 0; i < res.data.length; i++) {
                if (res.data[i].id == xb && typeof (res.data[i].markColor) != "undefined" && res.data[i].markColor != "") {
                    Layui_SetDataTableRowColor('tablediv', $(this).attr("data-index"), res.data[i].markColor);
                    colors = res.data[i].markColor;
                }
            }
            colorpicker.render({
                elem: this //绑定元素
                , color: colors //设置默认色
                , done: function (color) {//点击颜色选择器的“确认”和“清除”按钮，均会触发 done 回调，回调返回当前选择的色值
                    let index = $(this.elem).attr("data-index");
                    Layui_SetDataTableRowColor('tablediv', index, color);
                    //保存修改的颜色
                    let id = res.data[index].id;
                    let req = {
                        id: id,
                        color: color
                    }
                    $.ajax({
                        type: "POST",
                        dataType: "json",
                        contentType: 'application/json',
                        data: JSON.stringify(req),
                        url: "payment/updateMarkColor",
                        success: function (data) {
                            if (data.status == 200) {
                                layer.msg('修改成功');
                            } else {
                                layer.msg(data.msg);
                            }
                        }
                    });
                }

            });
        });
    }
});

if (paymentPurchaseNo!=""){
    $("#info").val(paymentPurchaseNo);
    let data={}
    data.info=purchaseNo;
    table.reload('maininformationtableid', {
        page: {
            limit: 300,
            curr: 1
        },
        url:'payment/getListByPage',
        where: data
    }, 'data');
}


//设置layui datatable的某一行的颜色
//DivId:datatable父div的 id;RowIndex:行序列号；Color：颜色字符串，如'#FF3030'
function Layui_SetDataTableRowColor(DivId, RowIndex, Color) {
    try {
        let div = document.getElementById(DivId);
        if (div != null) //找到对象了
        {
            let table_main = div.getElementsByClassName('layui-table-main');   //通过class获取table_main
            if (table_main != null && table_main.length > 0) {
                let table = table_main[0].getElementsByClassName('layui-table');   //通过class获取table
                if (table != null && table.length > 0) {
                    let trs = table[0].querySelectorAll("tr");
                    if (trs != null && trs.length > 0) {
                        trs[RowIndex].style.backgroundColor = Color;//背景颜色
                    }
                }
            }

        }
    } catch (e) {
        console.log(e.message);
    }
}


//监听复选框
table.on('checkbox(maininformationtable)', function (data) {
    let checkStatus = table.checkStatus("maininformationtableid").data;
    for(var i = 0;i<checkStatus.length;i++){
        if(checkStatus[i].statusStr == "已批箱"){
            $('.disabledbutton').attr('disabled',false);
            $('.disabledbutton').css("background","#009688")
            return false;
        }
    }
    $('.disabledbutton').attr('disabled',true);
    $('.disabledbutton').css("background","#b1b1b1");
});
table.on('tool(maininformationtable)', function(obj){
    let data = obj.data;
    let id = data.id;
    if(obj.event === 'update') {
        parent.intab("views/jsp/Money/tpl/updatePayment.jsp?id="+obj.data.id,"修改付款")
    }else if(obj.event === 'delect'){
        layer.confirm('确认删除？',confirmInfo(3,6), function (index) {
            layer.close(index);
            let dataBases={
                id:id,
                status:data.status
            }
            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:JSON.stringify(dataBases),
                url:"payment/delete",
                success:function(res){
                    if(res.status == 200){
                        layer.msg("删除成功", {icon: 6});
                        table.reload('maininformationtableid', {
                            page: {
                                curr: 1 //重新从第 1 页开始
                            }
                            ,where: data.field
                        }, 'data');
                        return false;
                    }else {
                        layer.msg(res.msg, {icon: 5});
                    }
                }
            });
        });
    }else if(obj.event === 'submits'){
        layer.confirm('确定提交审批吗', confirmInfo(3, 5), function (index) {
            operationData(data, 1, "提交审批");
        });
    }else if(obj.event === 'through'){
        layer.confirm('确定审批通过吗', confirmInfo(3, 5), function (index) {
            operationData(data, 2, "审批通过");
        });
    }else if(obj.event === 'backtothe'){
        layer.confirm('确定审批退回吗', confirmInfo(3, 5), function (index) {
            operationData(data, 3, "审批退回");
        });
    }else if(obj.event === 'complete'){
        layer.confirm('确定完成吗', confirmInfo(3, 5), function (index) {
            operationData(data, 4, "完成");
        });
    }else if(obj.event === 'reduction'){
        layer.confirm('确定还原吗', confirmInfo(3, 5), function (index) {
            operationData(data, 5, "还原");
        });
    }else if(obj.event === 'paymentsplit'){
        layer.open({
            type: 2,
            area: $(window).width() < 458 ? "['100%', '100%']" : ['95%', '95%'],
            content: 'views/jsp/Money/tpl/akeybreakuppayment.jsp?id='+obj.data.id
        });
    }else if(obj.event === 'arrangepayment'){
        //安排付款
        layer.open({
            type: 2,
            area: $(window).width() < 458 ? "['100%', '100%']" : ['95%', '95%'],
            content: 'views/jsp/Money/tpl/arrangepayment.jsp?id='+obj.data.id
        });
    }else if (obj.event === "paymentorderno"){
        parent.intab("views/jsp/Money/tpl/viewpayment.jsp?id="+obj.data.id,"查看付款单据")
    }
});

function operationData(data, operation, msg){
    let fields = {
        id : data.id,
        billNo : data.billNo,
        operation: operation
    }
    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:JSON.stringify(fields),
        url:"payment/operation",
        success:function(res){
            if(res.status == 200){
                layer.msg(msg, {icon: 6});
                table.reload('maininformationtableid', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where: data.field
                }, 'data');
                return false;
            }else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
}

form.on('submit(submitform)', function(data){
    table.reload('maininformationtableid', {
        page: {
            curr: 1 //重新从第 1 页开始
        }
        ,where: data.field
    }, 'data');
    return false;
});

table.on('toolbar(maininformationtable)', function(obj){
    let checkStatus = table.checkStatus(obj.config.id);
    switch(obj.event){
        case 'news':
            parent.intab("views/jsp/Money/tpl/newuppayment.jsp","登记付款");
            break;
        case 'print':
            if(checkStatus.data.length > 1){
                layer.msg( "每次只能打印一个单据! ");
                break;
            }
            if(checkStatus.data.length == 0){
                layer.msg("请选择要打印一个单据! ");
                break;
            }
            if(checkStatus.data[0].type==1){//预付款
                window.open("views/jsp/report.jsp?ym=prepaymentApplicationReport&code=code:"+checkStatus.data[0].id)
            }else if (checkStatus.data[0].type==2){//后付款
                window.open("views/jsp/report.jsp?ym=prepaymentBalanceReport&code=code:"+checkStatus.data[0].id)
            }

            break;
    };
});

function getIdByCheckStatus(checkStatus) {
    let id = "";
    if (checkStatus.length != 0) {
        for (let i = 0; i < checkStatus.length; i++) {
            if (i == checkStatus.length - 1) {
                id += checkStatus[i].id;
            } else {
                id += checkStatus[i].id + ",";
            }
        }
    }
    return id;
}

$("#refundregistration").on("click",function () {
    //退款登记
    //获取选中的数据
    let checkStatus = table.checkStatus("maininformationtableid").data;
    if (checkStatus.length == 0) {
        layer.msg("请选择数据")
        return false;
    }
    let id = getIdByCheckStatus(checkStatus);
    layer.open({
        type: 2,
        area: ['1488px', '800px'],
        content: 'views/jsp/Money/tpl/refundregistrationpayment.jsp?id=' + id
    });
});
$("#akeybreakup").on("click",function () {
    layer.open({
        type: 2,
        area: ['1488px', '800px'],
        content: 'views/jsp/Money/tpl/akeybreakuppayment.jsp'
    });
});
$("#statistical").on("click",function () {
    parent.intab("views/jsp/Money/tpl/statistics.jsp","付款统计")
});

//提示信息渲染
function confirmInfo(icon, anim) {
    let data = {
        icon: icon,
        title: "提示",
        offset: "auto",
        skin: 'layui-layer-molv',
        anim: anim
    }
    return data;
}
//判断当前登录用户是否有 工厂统计及费用方式 权限
function factory_statistics_cost(){
    $.ajax({
        url:'shipmentPlan/factoryStatisticsCost',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                factoryStatisticsCost=da.data;
            }
        }
    });
}
